package com.wp.targetOffer;

/**
 * Created by 王萍 on 2017/8/3 0003.
 */
public class 反转链表 {

    public static void main(String[] args) {

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;

        ListNode node = ReverseList(node1);
        printListNode(node);
    }

    private static void printListNode(ListNode node) {

        while (node != null) {
            System.out.print(node.val + "->");
            node = node.next;
        }
    }

    public static ListNode ReverseList(ListNode head) {

        if (head == null) return null;
        else {

            //用于记录临时节点的变量。
            ListNode preNode = null, nextNode;
            while (head != null) {
                nextNode = head.next;
                head.next = preNode;
                preNode = head;
                if (nextNode == null) return head;  //这里是判断是否遍历到了尾部，防止把返回的节点赋值成了空节点
                head = nextNode;
            }
        }
        return head;
    }

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}
